/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.zprofilefrontend.common.Util;
import com.vng.zing.zprofilefrontend.common.Validation;
import com.vng.zing.calc.thrift.GENDER;
import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ProfileSession;
import com.vng.zing.calc.thrift.ROLE;
import com.vng.zing.calc.thrift.SOURCE;
import com.vng.zing.calc.thrift.STATUS;
import com.vng.zing.logger.ZLogger;
import com.vng.zing.stats.Profiler;
import com.vng.zing.stats.ThreadProfiler;
import com.vng.zing.zcommon.thrift.PutPolicy;
import static com.vng.zing.zprofilefrontend.model.BaseModel.checkLogIn;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 *
 * @author namhh
 */
public class AjaxCreateModel extends BaseModel {

    private static final Logger _Logger = ZLogger.getLogger(LogInModel.class);
    public static final AjaxCreateModel Instance = new AjaxCreateModel();

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {

        ThreadProfiler profiler = Profiler.getThreadProfiler();
        if (null == req.getParameter("profile")) {
            return;
        }
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter out = null;
        try {
            req.setCharacterEncoding("UTF-8");
            out = resp.getWriter();
            ///TODO..
              ProfileSession profileSession = checkLogIn(req);
            if (null != profileSession) {
                out.println(Util.toJSON("SUCCESS", "/info?id=" + profileSession));
            } else {
                profiler.push(this.getClass(), "output");
                Map<String, Object> validateRes = validateProfile(req.getParameter("profile"));
                if ("SUCCESS".equals(validateRes.get("STATUS"))) {

                    Profile profile = (Profile) validateRes.get("MESSAGE");
                    Long createdDate = (new Date().getTime() / 1000);
                    profile.setCreatedDate(createdDate.intValue());
                    profile.setStatus(STATUS.ACTIVE);
                    profile.setModifiedBy(profile.getUsername());
                    profile.setRole(ROLE.USER);
                    profile.setModifiedDate(createdDate.intValue());
                    profile.setSource(SOURCE.LC);
                    profile = getClient().createProfile(profile);
                    if (null != profile) {
                        getClientWithCache().putCache(profile.getId(), profile, PutPolicy.ADD_OR_UDP);
                        setLoggedIn(req, resp,new ProfileSession(profile.getId()), false);
                        out.println(Util.toJSON("SUCCESS", "/info?id=" + profile.getId()));
                    } else {
                        out.println(Util.toJSON("ERROR", getProperties().get("en.create.Failed")));
                    }
                } else {
                    out.println(JSONObject.toJSONString(validateRes));
                }
            }
            profiler.pop(this.getClass(), "output");
        } catch (Exception ex) {
            _Logger.error(null, ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private Map<String, Object> validateProfile(String jsonData) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(jsonData);
            JSONObject jsonObject = (JSONObject) obj;
            Profile profile = new Profile();
            String message = "";

            if (null != jsonObject.get("username")) {
                String username = (String) jsonObject.get("username");

                if (Validation.validateUsername(username)) {
                    if (!this.getClient().validUsername(username)) {
                        message +=  getProperties().get("en.USERNAME_EXIST");
                    } else {
                        profile.setUsername(username);
                    }
                } else {
                    message +=  getProperties().get("en.INVALID_USERNAME");
                }

            } else {
                message +=  getProperties().get("en.INVALID_USERNAME");
            }

            if (null != jsonObject.get("password")) {
                String password = (String) jsonObject.get("password");
                if (Validation.validatePassword(password)) {
                    profile.setPassword(password);
                } else {
                    message +=  getProperties().get("en.INVALID_PASSWORD");
                }
            } else {
                message +=  getProperties().get("en.INVALID_PASSWORD");
            }

            if (null != jsonObject.get("displayName")) {
                String displayName = (String) jsonObject.get("displayName");
                if (Validation.validateDisplayName(displayName)) {
                    profile.setDisplayName(displayName);
                } else {
                    message +=  getProperties().get("en.INVALID_DISPLAYNAME");
                }
            } else {
                message +=  getProperties().get("en.INVALID_DISPLAYNAME");
            }

            if (null != jsonObject.get("email")) {
                String email = (String) jsonObject.get("email");
                if (Validation.validateEmail(email)) {
                    profile.setEmail(email);
                } else {
                    message +=  getProperties().get("en.INVALID_EMAIL");
                }
            } else {
                message += getProperties().get("en.INVALID_EMAIL");
            }

            if (null != jsonObject.get("cityId") || Util.isShort((String) jsonObject.get("cityId"))) {
                 Short cityId = Short.parseShort((String) jsonObject.get("cityId"));
                if (null == CityModel.getInstance().getAllCities().get(cityId)) {
                    message += getProperties().get("en.INVALID_CITY");
                } else {
                    profile.setCityId(Short.parseShort((String) jsonObject.get("cityId")));
                }
                
            } else {

            }

            if (null != jsonObject.get("dateOfBirth") || Util.isInteger((String) jsonObject.get("dateOfBirth"))) {
                Long dateOfBirth = (Long) jsonObject.get("dateOfBirth");
                if (Validation.validateDateOfBirth(dateOfBirth.intValue())) {
                    profile.setDateOfBirth(dateOfBirth.intValue());
                } else {
                    message += getProperties().get("en.INVALID_DATEOFBIRTH");
                }
            } else {
                message += getProperties().get("en.INVALID_DATEOFBIRTH");
            }

            if (null != jsonObject.get("mobile")) {
                String mobile = (String) jsonObject.get("mobile");
                if (Validation.validateMobile(mobile)) {
                    profile.setMobileNumber(mobile);
                } else {
                    message += getProperties().get("en.INVALID_MOBILE");
                }
            } else {
                message += getProperties().get("en.INVALID_MOBILE");
            }

            if (null != jsonObject.get("gender") || Util.isShort((String) jsonObject.get("gender"))) {
                Short gender = Short.parseShort((String) jsonObject.get("gender"));
                profile.setGender(GENDER.findByValue(gender));
            } else {

            }
            if ("".equals(message)) {
                ret.put("STATUS", "SUCCESS");
                ret.put("MESSAGE", profile);
            } else {
                ret.put("STATUS", "ERROR");
                ret.put("MESSAGE", message);
            }
            return ret;
        } catch (Exception ex) {
            ret.put("STATUS", "ERROR");
            ret.put("MESSAGE", ex.toString());
            _Logger.error("validate profile " + ex.toString());
        }
        return ret;
    }

}
